const { query } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');
const { validate } = require('../../../lib/validation');
const Joi = require('joi');

// CI项目创建验证Schema
const createCiItemSchema = Joi.object({
  ci_code: Joi.string().max(50).required(),
  ci_name: Joi.string().max(100).required(),
  ci_type: Joi.string().valid('server', 'application', 'database', 'network', 'storage', 'security', 'other').required(),
  category: Joi.string().max(50),
  location: Joi.string().max(200),
  ip_address: Joi.string().max(45).ip(),
  hostname: Joi.string().max(100),
  environment: Joi.string().valid('production', 'staging', 'testing', 'development').default('production'),
  vendor: Joi.string().max(100),
  model: Joi.string().max(100),
  owner_department: Joi.string().max(100),
  business_importance: Joi.string().valid('critical', 'high', 'medium', 'low').default('medium'),
  description: Joi.string(),
  status: Joi.string().valid('active', 'inactive', 'maintenance', 'retired').default('active')
});

async function handler(req, res) {
  try {
    switch (req.method) {
      case 'GET':
        return await getCiItems(req, res);
      case 'POST':
        return await createCiItem(req, res);
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('CI项目API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

async function getCiItems(req, res) {
  try {
    // Simplified query for debugging
    const ciItems = await query('SELECT * FROM ci_items LIMIT 10');
    
    res.status(200).json({
      success: true,
      data: ciItems
    });
  } catch (error) {
    console.error('CI Items query error:', error);
    res.status(500).json({
      success: false,
      message: 'Database query failed',
      error: error.message
    });
  }
}

async function createCiItem(req, res) {
  const validation = validate(createCiItemSchema, req.body);
  if (!validation.isValid) {
    return res.status(400).json({
      success: false,
      message: '请求数据验证失败',
      errors: validation.errors
    });
  }

  const {
    ci_code,
    ci_name,
    ci_type,
    category,
    location,
    ip_address,
    hostname,
    environment,
    vendor,
    model,
    owner_department,
    business_importance,
    description,
    status
  } = validation.data;

  const result = await query(`
    INSERT INTO ci_items (
      ci_code, ci_name, ci_type, category, location, ip_address, 
      hostname, environment, vendor, model, owner_department, 
      business_importance, description, status
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `, [
    ci_code, ci_name, ci_type, category, location, ip_address,
    hostname, environment, vendor, model, owner_department,
    business_importance, description, status
  ]);

  const newCiItem = await query('SELECT * FROM ci_items WHERE id = ?', [result.insertId]);

  res.status(201).json({
    success: true,
    message: 'CI项目创建成功',
    data: newCiItem[0]
  });
}

export default authenticateToken(handler);